package com.chaoyue.auth.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chaoyue.auth.beans.dto.AuthParamsDto;
import com.chaoyue.auth.beans.dto.CyUserExt;
import com.chaoyue.auth.beans.po.CyUser;
import com.chaoyue.auth.ucenter.feignclient.CheckCodeClient;
import com.chaoyue.auth.ucenter.mapper.CyUserMapper;

import com.chaoyue.auth.ucenter.service.AuthService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@SuppressWarnings({"all"})
/**
 * @author whr
 * @version 1.0
 * @description: 账号密码登录service
 * @date 2023/5/28 21:17
 */
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {
    @Autowired
    private CyUserMapper xcUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private CheckCodeClient checkCodeClient;

    @Override
    public CyUserExt execute(AuthParamsDto authParamsDto) {
        //获取用户名密码
        String username = authParamsDto.getUsername();
        String password = authParamsDto.getPassword();
        //获取验证码的key和value
//        String checkcode = authParamsDto.getCheckcode();
//        String checkcodekey = authParamsDto.getCheckcodekey();
//        if(StringUtils.isBlank(checkcode)||StringUtils.isBlank(checkcodekey)){
//          throw new RuntimeException("验证码为空");
//        }
//        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
//        if(verify==null||!verify){
//            throw new RuntimeException("验证码输入有误");
//        }
        //查询用户
        LambdaQueryWrapper<CyUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(username != null, CyUser::getUsername, username);
        CyUser user = xcUserMapper.selectOne(queryWrapper);
        //该用户不存在，直接返回null，spring security会抛出异常用户不存在
        if (user == null) {
            throw new RuntimeException("该用户不存在");
        }
        String passwordDb = user.getPassword();
        boolean matches = passwordEncoder.matches(password, passwordDb);
        if (!matches) {
            throw new RuntimeException("用户名或密码错误");
        }
        CyUserExt xcUserExt = new CyUserExt();
        BeanUtils.copyProperties(user, xcUserExt);
        return xcUserExt;
    }

}
